package com.cmnit.utils

import java.sql.{Connection, PreparedStatement, ResultSet, SQLException}

import org.apache.log4j.Logger

object MySqlUtils {

  final val logger = Logger.getLogger(MySqlUtils.getClass)

  /**
   * 执行SQL
   *
   * @param sql sql语句
   * @return
   */
  def execute(sql: String, connect: Connection): Unit = {
    var pstmt: PreparedStatement = null
    logger.info("执行SQL=>" + sql)
    try {
      pstmt = connect.prepareStatement(sql)
      pstmt.execute
    } catch {
      case e: Exception => println(e)
    } finally {
      closeResource(pstmt, connect)
    }
  }

  // 提供关闭资源的方法 【connection是归还到连接池】
  private def closeResource(resultSet: ResultSet, preparedStatement: PreparedStatement, connection: Connection): Unit = {
    // 关闭结果集
    closeResultSet(resultSet)
    // 关闭语句执行者
    closePrepareStatement(preparedStatement)
    // 关闭连接
    closeConnection(connection)
  }

  /**
   * 关闭连接
   *
   * @param preparedStatement pstm
   * @param connection        connect
   */
  def closeResource(preparedStatement: PreparedStatement, connection: Connection): Unit = {
    closePrepareStatement(preparedStatement)
    closeConnection(connection)
  }

  /**
   * 关闭连接
   *
   * @param connection connect
   */
  private def closeConnection(connection: Connection): Unit = {
    if (connection != null) try connection.close()
    catch {
      case e: SQLException =>
        e.printStackTrace()
    }
  }

  /**
   * 关闭连接
   *
   * @param preparedStatement pstm
   */
  private def closePrepareStatement(preparedStatement: PreparedStatement): Unit = {
    if (preparedStatement != null) try preparedStatement.close()
    catch {
      case e: SQLException =>
        e.printStackTrace()
    }
  }

  /**
   * 关闭连接
   *
   * @param resultSet result
   */
  private def closeResultSet(resultSet: ResultSet): Unit = {
    if (resultSet != null) try resultSet.close()
    catch {
      case e: SQLException =>
        e.printStackTrace()
    }
  }
}
